package com.allwees.bs.c.module.order.context.listener;

import com.allwees.bs.c.module.ops.service.UserCouponService;
import com.allwees.bs.c.module.order.context.event.OrderCreatedEvent;
import com.allwees.bs.c.module.order.dto.OrderDTO;
import com.allwees.bs.c.module.order.repository.CartRepository;
import com.allwees.bs.c.module.order.service.CartService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.transaction.event.TransactionalEventListener;

/**
 * @author yangylsky
 * @since 2019-08-17
 */
@Slf4j
@Component
public class OrderCreatedListener {

    @Autowired
    private CartService cartService;

    @Autowired
    private UserCouponService userCouponUseService;

    @Autowired
    private CartRepository cartRepository;

    @Async
    @TransactionalEventListener
    public void onOrderCreated(OrderCreatedEvent event) {

        OrderDTO order = (OrderDTO) event.getSource();

        log.info("reveive order create event[orderUuid:{}]", order.getUuid());

        //clearUserCart(order.getUserUuid());

        //useUserCoupon(order.getUserCouponUuid());
    }


    private void clearUserCart(String userUuid) {
        cartService.clearUserCart(userUuid);
    }

    private void useUserCoupon(String userCouponUuid) {
        if (StringUtils.isBlank(userCouponUuid)) {
            return;
        }
        userCouponUseService.use(userCouponUuid);
    }
}
